package org.googlecode.viewt.core.dao;

import org.googlecode.viewt.core.SpringContextHelper;
import org.googlecode.viewt.core.exception.BeanCreateException;
import org.googlecode.viewt.core.exception.ContextInitException;
import org.googlecode.viewt.core.po.POUtils;
import org.googlecode.viewt.core.tools.dao.DAOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DAOFactory {
	public static IDAO getDAO(String poClassName) throws DAOObtainException {
		return getDAO(poClassName, null);
	}

	public static IDAO getDAO(Class poClass) throws DAOObtainException {
		return getDAO(poClass, null);
	}

	public static IDAO getDAO(String poClassName, String owner)
			throws DAOObtainException {
		String shortClass = POUtils.shortClassName(poClassName);
		if ((shortClass != null) && (shortClass.charAt(0) == 'I')) {
			poClassName = POUtils.getPackageName(poClassName) + "."
					+ shortClass.substring(1);
		}
		return getDAOByBeanName(DAOUtils.getDAOBeanName(poClassName, owner));
	}

	public static IDAO getDAO(Class poClass, String owner)
			throws DAOObtainException {
		return getDAO(poClass.getName(), owner);
	}

	public static IDAO getDAOByBeanName(String beanName)
			throws DAOObtainException {
		Logger logger = LoggerFactory.getLogger(DAOFactory.class);
		try {
			return ((IDAO) SpringContextHelper.getBean(beanName));
		} catch (ContextInitException contextEx) {
			logger.error("Get DAO fail, initialize spring context error",
					contextEx);
			throw new DAOObtainException(
					"Get DAO fail, initialize spring context error", contextEx);
		} catch (BeanCreateException beanEx) {
			logger.error("Get DAO fail, create bean error", beanEx);
			throw new DAOObtainException("Get DAO fail, create bean error",
					beanEx);
		}
	}
}